<template>
  <div
    class="h-[50px] bottom-10 text-[14px] flex items-center color-[#32373c] dark:color-[#fff] font-bold btn-container"
  >
    <!-- 【通过】按钮 -->
    <el-popover
      :visible="popOverVisible.approve"
      placement="top-end"
      :width="420"
      trigger="click"
      v-if="runningTask && isHandleTaskStatus() && isShowButton(OperationButtonType.APPROVE)"
    >
      <template #reference>
        <el-button plain type="success" @click="openPopover('approve')" icon="select">
          {{ getButtonDisplayName(OperationButtonType.APPROVE) }}
        </el-button>
      </template>
      <!-- 审批表单 -->
      <div class="flex flex-col flex-1 pt-20px px-20px" v-loading="formLoading">
        <el-form
          label-position="top"
          class="mb-auto"
          ref="approveFormRef"
          :model="approveReasonForm"
          :rules="approveReasonRule"
          label-width="100px"
        >
          <el-card v-if="runningTask?.formId > 0" class="mb-15px !-mt-10px">
            <template #header>
              <span class="el-icon-picture-outline"> 填写表单【{{ runningTask?.formName }}】 </span>
            </template>
  
          </el-card>
          <el-form-item label="审批意见" prop="reason">
            <el-input
              v-model="approveReasonForm.reason"
              placeholder="请输入审批意见"
              type="textarea"
              :rows="4"
            />
          </el-form-item>
          <el-form-item>
            <el-button :disabled="formLoading" type="success" @click="handleAudit(true, approveFormRef)">
              {{ getButtonDisplayName(OperationButtonType.APPROVE) }}
            </el-button>
            <el-button @click="closePropover('approve', approveFormRef)"> 取消 </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-popover>

    <!-- 【拒绝】按钮 -->
    <el-popover
      :visible="popOverVisible.reject"
      placement="top-end"
      :width="420"
      trigger="click"
      v-if="runningTask && isHandleTaskStatus() && isShowButton(OperationButtonType.REJECT)"
    >
      <template #reference>
        <el-button class="mr-20px" plain type="danger" @click="openPopover('reject')"  icon="close">
           {{ getButtonDisplayName(OperationButtonType.REJECT) }}
        </el-button>
      </template>
      <!-- 审批表单 -->
      <div class="flex flex-col flex-1 pt-20px px-20px" v-loading="formLoading">
        <el-form
          label-position="top"
          class="mb-auto"
          ref="rejectFormRef"
          :model="rejectReasonForm"
          :rules="rejectReasonRule"
          label-width="100px"
        >
          <el-form-item label="审批意见" prop="reason">
            <el-input
              v-model="rejectReasonForm.reason"
              placeholder="请输入审批意见"
              type="textarea"
              :rows="4"
            />
          </el-form-item>
          <el-form-item>
            <el-button :disabled="formLoading" type="danger" @click="handleAudit(false,rejectFormRef)">
              {{ getButtonDisplayName(OperationButtonType.REJECT) }}
            </el-button>
            <el-button @click="closePropover('reject', rejectFormRef)"> 取消 </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-popover>

    <!-- 【退回】按钮 -->
    <!-- <el-popover
      :visible="popOverVisible.return"
      placement="top-start"
      :width="420"
      trigger="click"
      v-if="runningTask && isHandleTaskStatus() && isShowButton(OperationButtonType.RETURN)"
    >
      <template #reference>
        <div @click="openPopover('return')" class="hover-bg-gray-100 rounded-xl p-[6px]" >
          <el-icon><Back /></el-icon>&nbsp;
          {{ getButtonDisplayName(OperationButtonType.RETURN) }}
        </div>
      </template>
      <div class="flex flex-col flex-1 pt-[20px] px-[20px]" v-loading="formLoading">
        <el-form
          label-position="top"
          class="mb-auto"
          ref="returnFormRef"
          :model="returnForm"
          :rules="returnFormRule"
          label-width="100px"
        >
          <el-form-item label="退回节点" prop="targetTaskDefinitionKey">
            <el-select v-model="returnForm.targetTaskDefinitionKey" clearable style="width: 100%">
              <el-option
                v-for="item in returnList"
                :key="item.taskDefinitionKey"
                :label="item.name"
                :value="item.taskDefinitionKey"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="退回理由" prop="returnReason">
            <el-input
              v-model="returnForm.returnReason"
              clearable
              placeholder="请输入退回理由"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
          <el-form-item>
            <el-button :disabled="formLoading" type="primary" @click="handleReturn()" >
              {{ getButtonDisplayName(OperationButtonType.RETURN) }}
            </el-button>
            <el-button @click="closePropover('return', returnFormRef)" > 取消 </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-popover> -->

 

   <el-button   link
            type="primary"  @click="open()"
              >查看详情
              <el-icon >
                <CaretTop v-show="detailOpen" />
                <CaretBottom v-show="!detailOpen" />
              </el-icon>
            </el-button>
             <el-button
            link
            type="primary"
            @click="handleDetail(scope.row)"
          >
           
          </el-button>

    <!--【取消】按钮 这个对应发起人的取消, 只有发起人可以取消 -->
    <!-- <el-popover
      :visible="popOverVisible.cancel"
      placement="top-start"
      :width="420"
      trigger="click"
      v-if="
        userId === processInstance?.startUser?.userId && !isEndProcessStatus(processInstance?.status)
      "
    >
      <template #reference>
        <div @click="openPopover('cancel')" class="hover-bg-gray-100 rounded-xl p-[6px]">
        <svg-icon  icon-class="mail-reply" /> &nbsp;取消
        </div>
      </template>
      <div class="flex flex-col flex-1 pt-[20px] px-[20px]" v-loading="formLoading">
        <el-form
          label-position="top"
          class="mb-auto"
          ref="cancelFormRef"
          :model="cancelForm"
          :rules="cancelFormRule"
          label-width="100px"
        >
          <el-form-item label="取消理由" prop="cancelReason">
            <span class="text-#878c93 text-12px">&nbsp; 取消后，该审批流程将自动结束</span>
            <el-input
              v-model="cancelForm.cancelReason"
              clearable
              placeholder="请输入取消理由"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
          <el-form-item>
            <el-button :disabled="formLoading" type="primary" @click="handleCancel()">
              确认
            </el-button>
            <el-button @click="closePropover('cancel', cancelFormRef)"> 取消 </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-popover> -->
    <!-- 【再次提交】 按钮-->
    <!-- <div
      @click="handleReCreate()"
      class="hover-bg-gray-100 rounded-xl p-[6px]"
      v-if="
        userId === processInstance?.startUser?.userId &&
        isEndProcessStatus(processInstance?.status) 
       
      "
    >
     <el-icon >
      <refresh />
        <span> 再次提交</span>
    </el-icon>
     
    </div> -->
  </div>
</template>
<script  setup name="BpmProcessInstanceDetailOpertion">
import useUserStore from "@/store/modules/user";
import {
  rejectTaskyudao,
  complete,
  rejectTask,
  returnTask,
  returnTaskyudao,
  getTaskListByReturn,
  approveTask,
  todoList,
} from "@/api/flowable/todo";
import{cancelProcessInstanceByStartUser}from "@/api/flowable/instance";
const userStore = useUserStore();
const BpmProcessInstanceStatus = {
  NOT_START: -1, // 未开始
  RUNNING: 1, // 审批中
  APPROVE: 2, // 审批通过
  REJECT: 3, // 审批不通过
  CANCEL: 4 // 已取消
}
const detailOpen = ref(false);

const  OperationButtonType= {
  /**
   * 通过
   */
  APPROVE : 1,
  /**
   * 拒绝
   */
  REJECT : 2,
  /**
   * 转办
   */
  TRANSFER : 3,
  /**
   * 委派
   */
  DELEGATE : 4,
  /**
   * 加签
   */
  ADD_SIGN : 5,
  /**
   * 退回
   */
  RETURN : 6,
  /**
   * 抄送
   */
  COPY : 7
}
 const OPERATION_BUTTON_NAME = new Map()
OPERATION_BUTTON_NAME.set(OperationButtonType.APPROVE, '通过')
OPERATION_BUTTON_NAME.set(OperationButtonType.REJECT, '拒绝')
OPERATION_BUTTON_NAME.set(OperationButtonType.TRANSFER, '转办')
OPERATION_BUTTON_NAME.set(OperationButtonType.DELEGATE, '委派')
OPERATION_BUTTON_NAME.set(OperationButtonType.ADD_SIGN, '加签')
OPERATION_BUTTON_NAME.set(OperationButtonType.RETURN, '退回')
OPERATION_BUTTON_NAME.set(OperationButtonType.COPY, '抄送')

// 操作按钮类型枚举 (用于审批节点)


const router = useRouter() // 路由
// const message = useMessage() // 消息弹窗

 const { proxy } = getCurrentInstance();

const userId =  userStore.id; // 当前登录的编号

const emit = defineEmits(['success','opentail']) // 定义 success 事件，用于操作成功后的回调

const props = defineProps({
  processInstance: {},  // 流程实例信息
  processDefinition: {},  // 流程定义信息
  userOptions: [],
  normalForm: String, // 流程表单 formCreate
  normalFormApi: String, // 流程表单 formCreate Api
  writableFields: [], // 流程表单可以编辑的字段
  isView:Boolean,
    
})



const formLoading = ref(false) // 表单加载中
const popOverVisible = ref({
  approve: false,
  reject: false,
  transfer: false,
  delegate: false,
  addSign: false,
  return: false,
  copy: false,
  cancel: false,
  deleteSign: false
}) // 气泡卡是否展示
const returnList = ref([]) // 退回节点

// ========== 审批信息 ==========
const runningTask = ref() // 运行中的任务
const approveForm = ref({}) // 审批通过时，额外的补充信息
const approveFormFApi = ref({}) // approveForms 的 fAPi

// 审批通过意见表单
const approveFormRef = ref()
const approveReasonForm = reactive({
  reason: ''
})
const approveReasonRule = reactive({
  reason: [{ required: true, message: '审批意见不能为空', trigger: 'blur' }],
})
// 拒绝表单
const rejectFormRef = ref()
const rejectReasonForm = reactive({
  reason: ''
})
const rejectReasonRule = reactive({
  reason: [{ required: true, message: '审批意见不能为空', trigger: 'blur' }],
})




// 退回表单
const returnFormRef = ref()
const returnForm = reactive({
  targetTaskDefinitionKey: undefined,
  returnReason: ''
})
const returnFormRule = reactive({
  targetTaskDefinitionKey: [{ required: true, message: '退回节点不能为空', trigger: 'change' }],
  returnReason: [{ required: true, message: '退回理由不能为空', trigger: 'blur' }]
})

// 取消表单
const cancelFormRef = ref()
const cancelForm = reactive({
  cancelReason: ''
})
const cancelFormRule = reactive({
  cancelReason: [{ required: true, message: '取消理由不能为空', trigger: 'blur' }],
})

/** 监听 approveFormFApis，实现它对应的 form-create 初始化后，隐藏掉对应的表单提交按钮 */


/** 弹出气泡卡 */
const openPopover = async (type) => {
  if (type === 'approve') {
    // 校验流程表单
    //  const valid = await validateNormalForm();
    //  if (!valid) {
    //   message.warning('表单校验不通过，请先完善表单!!')
    //   return;
    //  }
  }
  if (type === 'return') {
    // 获取退回节点
    var  data= await getTaskListByReturn({taskId:runningTask.value.id})
    returnList.value = data.data
    if (returnList.value.length === 0) {
     // message.warning('当前没有可退回的节点')
       proxy.$modal.msgWarning("当前没有可退回的节点");
      return
    }
  }
  Object.keys(popOverVisible.value).forEach((item) => {
    popOverVisible.value[item] = item === type
  })
  // await nextTick()
  // formRef.value.resetFields()
}

/** 关闭气泡卡 */
const closePropover = (type, formRef) => {
  if (formRef) {
    formRef.resetFields()
  } 
  popOverVisible.value[type] = false
}

/** 处理审批通过和不通过的操作 */
const handleAudit = async (pass, formRef) => {
  formLoading.value = true
  try {
    // 校验表单
    if (!formRef) return
    await formRef.validate()
    if (pass) {
       // 获取修改的流程变量, 暂时只支持流程表单
      // const variables = getUpdatedProcessInstanceVaiables();
      // 审批通过数据
      const data = {
        id: runningTask.value.id,
        reason: approveReasonForm.reason,
         // 审批通过, 把修改的字段值赋于流程实例变量
      }
      // 多表单处理，并且有额外的 approveForm 表单，需要校验 + 拼接到 data 表单里提交
      // TODO 芋艿 任务有多表单这里要如何处理，会和可编辑的字段冲突
      // const formCreateApi = approveFormFApi.value
      // if (Object.keys(formCreateApi)?.length > 0) {
      //   await formCreateApi.validate()
      //   // @ts-ignore
      //   data.variables = approveForm.value.value
      // }
      await  approveTask(data)
      popOverVisible.value.approve = false
       proxy.$modal.msgSuccess("审批通过成功");
     // message.success('审批通过成功')
    } else {
       // 审批不通过数据
       const data = {
        id: runningTask.value.id,
        reason: rejectReasonForm.reason,
      }
      await rejectTaskyudao(data)
      popOverVisible.value.reject = false
     // message.success('审批不通过成功')
       proxy.$modal.msgSuccess("审批不通过成功");
    }
    // 重置表单
    //formRef.resetFields()
    // 加载最新数据
    reload()
  } finally {
    formLoading.value = false
  }
}



const open =()=>{
  detailOpen.value = !detailOpen.value
  emit('opentail')

}


/** 处理退回 */
const handleReturn = async () => {
  formLoading.value = true
  try {
    // 1.1 校验表单
    if (!returnFormRef.value) return
    await returnFormRef.value.validate()
    // 1.2 提交退回
    const data = {
      id: runningTask.value.id,
      reason: returnForm.returnReason,
      targetTaskDefinitionKey: returnForm.targetTaskDefinitionKey
    }

    await returnTaskyudao(data)
    popOverVisible.value.return = false
    returnFormRef.value.resetFields()
     proxy.$modal.msgSuccess("操作成功");
    //message.success('操作成功')
    // 2 重新加载数据
    reload()
  } finally {
    formLoading.value = false
  }
}

/** 处理取消 */
const handleCancel = async () => {
  formLoading.value = true
  try {
    // 1.1 校验表单
    if (!cancelFormRef.value) return
    //await cancelFormRef.value.validate()
    // 1.2 提交取消
    await cancelProcessInstanceByStartUser(
      {
    id: props.processInstance.id,
    reason:  cancelForm.cancelReason
     }
    )
    popOverVisible.value.return = false
    proxy.$modal.msgSuccess('操作成功')
    //cancelFormRef.value.resetFields()
    // 2 重新加载数据
    reload()
  } finally {
    formLoading.value = false
  }
}

/** 处理再次提交 */
const handleReCreate = async () => {
  // 跳转发起流程界面
  await router.push({
    name: 'BpmProcessInstanceCreate',
    query: { processInstanceId: props.processInstance?.id }
  })
}



/** 重新加载数据 */
const reload = () => {
  emit('success')
}

/** 任务是否为处理中状态 */
const isHandleTaskStatus = () => {
  let canHandle = false
  if (1 === runningTask.value?.status) {
    canHandle = true
  }
  return canHandle
}

/** 流程状态是否为结束状态 */
const isEndProcessStatus = (status) => {
  let isEndStatus = false
  if (
    BpmProcessInstanceStatus.APPROVE === status ||
    BpmProcessInstanceStatus.REJECT === status ||
    BpmProcessInstanceStatus.CANCEL === status
  ) {
    isEndStatus = true
  }
  return isEndStatus
}

/** 是否显示按钮 */
const isShowButton = (btnType) => {
  let isShow = true
   if (runningTask.value?.buttonsSetting && runningTask.value?.buttonsSetting[btnType]) {
    isShow = runningTask.value.buttonsSetting[btnType].enable
  }
  return isShow
}

/** 获取按钮的显示名称 */
const getButtonDisplayName = (btnType) => {
  let displayName = OPERATION_BUTTON_NAME.get(btnType)
  if (runningTask.value?.buttonsSetting && runningTask.value?.buttonsSetting[btnType]) {
    displayName = runningTask.value.buttonsSetting[btnType].displayName
  }
  return displayName
}

const loadTodoTask = (task) => {
  approveForm.value = {}
  approveFormFApi.value = {}
  runningTask.value = task
  // 处理 approve 表单.
  if (task && task.formId && task.formConf) {
    const tempApproveForm = {}
    setConfAndFields2(tempApproveForm, task.formConf, task.formFields, task.formVariables)
    approveForm.value = tempApproveForm
  } else {
    approveForm.value = {} // 占位，避免为空
  }
}

/** 校验流程表单 */
const validateNormalForm = async () => {
  if (props.processDefinition?.formType === BpmModelFormType.NORMAL) {
    let valid = true
    try {
      await props.normalFormApi?.validate()
    } catch {
      valid = false;
    }
    return valid;
  } else {
    return true;
  }
}
/** 从可以编辑的流程表单字段，获取需要修改的流程实例的变量 */
const getUpdatedProcessInstanceVaiables = ()=> {
  const variables = {}
  props.writableFields.forEach( (field) => {
    const fieldValue = props.normalFormApi.getValue(field)
    variables[field] = fieldValue;
  })
  return variables
}

defineExpose({ loadTodoTask })
</script>

<style lang="scss" scoped>
:deep(.el-affix--fixed) {
  background-color: var(--el-bg-color);
}

.btn-container {
  > div {
    display: flex;
    margin: 0 8px;
    cursor: pointer;
    align-items: center;

    &:hover {
      color: #6db5ff;
    }
  }
}
</style>
